package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * 自定义拦截器，注入创建人，创建日期，修改人，修改日期
 *
 * @author athena
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class HandleBaseInfoInterceptor implements Interceptor {

    private static Logger logger = LoggerFactory.getLogger(HandleBaseInfoInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        //获取sql执行类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        // 用户类不处理，会导致获取不到用户信息出错
        if (args[1] instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) args[1];
            String username = null;
            try {
                //获取获取登陆信息
                username = SecurityUtils.getUsername();
            } catch (Exception e) {
                //为获取到不操作
                return invocation.proceed();
            }
            if (sqlCommandType == SqlCommandType.UPDATE) {
                baseEntity.setUpdateTime(DateUtils.getNowDate());
                baseEntity.setUpdateBy(username);
            } else if (sqlCommandType == SqlCommandType.INSERT) {
                baseEntity.setCreateTime(DateUtils.getNowDate());
                baseEntity.setCreateBy(username);
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        logger.debug("setProperties====>" + properties);
    }
}
